package io.plus.interactive.collections;

import drds.common.Clock;
import drds.common.Time;
import io.plus.interactive.Configuration;
import io.plus.interactive.Io;
import io.plus.server.ServerConfiguration;
import io.plus.utils.cache.caffeine.CaffeineCache;

import java.util.Collection;
import java.util.function.Consumer;

public class IpBlackList {
    public final static IpBlackList GLOBAL = new IpBlackList();
    private final static String CACHE_NAME_PREFIX = "ip_black_list";
    private final static Long TIME_TO_LIVE_SECONDS = Time.day * 120;
    private final static Long TIME_TO_IDLE_SECONDS = null;
    private String id;
    private String cacheName = null;
    private CaffeineCache cache = null;
    private ServerConfiguration serverConfiguration;

    private IpBlackList() {
        this.id = "__global__";
        this.cacheName = CACHE_NAME_PREFIX + this.id;
        this.cache = CaffeineCache.register(this.cacheName, TIME_TO_LIVE_SECONDS, TIME_TO_IDLE_SECONDS, null);
    }

    public IpBlackList(String id, ServerConfiguration serverConfiguration) {
        this.id = id;
        this.serverConfiguration = serverConfiguration;
        this.cacheName = CACHE_NAME_PREFIX + this.id;
        this.cache = CaffeineCache.register(this.cacheName, TIME_TO_LIVE_SECONDS, TIME_TO_IDLE_SECONDS, null);
    }

    public boolean add(String ip) {
        //先添加到黑名单列表
        cache.put(ip, Clock.currentTimeMillis);

        if (serverConfiguration != null) {
            //删除相关连接
            Io.remove(serverConfiguration, ip, "ip[" + ip + "]被加入了黑名单, " + serverConfiguration.getName());
        } else {
            Configuration.ALL_SERVER_GROUPCONTEXTS.stream().forEach(new Consumer<ServerConfiguration>() {
                @Override
                public void accept(ServerConfiguration tioConfig) {
                    Io.remove(tioConfig, ip, "ip[" + ip + "]被加入了黑名单, " + tioConfig.getName());

                }
            });
        }

        return true;
    }

    public void clear() {
        cache.clear();
    }

    public Collection<String> getAll() {
        return cache.keys();
    }

    /**
     * 是否在黑名单中
     */
    public boolean isInBlacklist(String ip) {
        return cache.get(ip) != null;
    }

    /**
     * 从黑名单中删除
     */
    public void remove(String ip) {
        cache.remove(ip);
    }
}
